from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response

from .models import Favor
from .serializer import FavorSerializer, FavorDetailSerializer
from rest_framework import viewsets, mixins, status


# Create your views here.

class FavorViewSet(viewsets.ModelViewSet):
    serializer_class = FavorSerializer

    def get_queryset(self):
        queryset = Favor.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_favor_count(self, request, *args, **kwargs):
        video_id = kwargs.get('pk')  # 从URL参数中获取视频的ID
        user_id = kwargs.get('user')  # 从URL参数中获取user的ID
        filters = Q(video_id=video_id) & Q(is_active=True)
        favor_count = Favor.objects.filter(filters).count()  # 查询点赞数量
        filters = Q(video_id=video_id) & Q(is_active=True) & Q(user_id=user_id)
        is_favored = len(Favor.objects.filter(filters)) != 0
        return Response({'favor_count': favor_count, 'is_favored': is_favored}, status=status.HTTP_200_OK)


class FavorDetailViewSet(viewsets.ModelViewSet):
    serializer_class = FavorDetailSerializer

    def get_queryset(self):
        queryset = Favor.objects.all()
        params = self.request.query_params
        if params:
            filters = {}
            for key, value in params.items():
                filters[key] = value
            queryset = queryset.filter(**filters)
        return queryset

    def get_my_favor(self, request, *args, **kwargs):
        user = kwargs.get('user')
        num = kwargs.get('num')
        from_index = kwargs.get('from')
        favors = Favor.objects.filter(user_id=user).filter(is_active=True).order_by('-time')
        result = []
        index = 0
        for i in range(from_index, from_index + num):
            if i >= len(favors):
                break
            result.append(FavorDetailSerializer(favors[i]).data)
            index += 1
        return Response({'favors': result, 'count': len(favors)}, status=status.HTTP_200_OK)
